import axios from "axios"
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user.js'
import router from "@/router"


const httpInstance = axios.create({
    //基地址
    baseURL: "http://pcapi-xiaotuxian-front-devtest.itheima.net",
    //超时时间
    timeout: 5000
})

//* token 请求拦截器  和后端约定好就行
httpInstance.interceptors.request.use(config => {
    // if (userStore.userInfo.token) {
    //     config.headers.Authorization = `Bearer ${userStore.userInfo.token}`
    // }
    return config
}, error => {
    return Promise.reject(error)
})

//*响应拦截器       401时配置token无效处理
httpInstance.interceptors.response.use(response => {
    //响应成功
    return response.data
}, error => {
    //响应失败  统一提示  其他地方不提示了
    if (error.response.status === 401) {
        const userStore = useUserStore()

        userStore.clearUserInfo()
    
        router.push('/login')
    }
    ElMessage({
        type: 'error',
        message: error.response.data.message
    })
    return Promise.reject(error)
})



export default httpInstance